<template>
  <div class="message-center">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item :to="{ path: '/dashboard' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>消息通知</el-breadcrumb-item>
      <el-breadcrumb-item>消息中心</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- WebSocket连接状态指示器 -->
    <div class="ws-status-indicator">
      <el-tooltip :content="wsConnected ? '实时消息已连接' : '实时消息连接已断开'" placement="bottom">
        <div :class="['status-dot', wsConnected ? 'connected' : 'disconnected']">
          <span class="status-text">{{ wsConnected ? '实时连接' : '连接断开' }}</span>
        </div>
      </el-tooltip>
    </div>

    <el-row :gutter="20" class="main-container">
      <!-- 左侧消息分类导航 -->
      <el-col :span="5" class="sidebar">
        <el-card class="category-card">
          <template #header>
            <div class="card-header">
              <span>消息分类</span>
              <el-button
                type="text"
                size="small"
                icon="Setting"
                @click="showSettingsDialog"
              >
                设置
              </el-button>
            </div>
          </template>

          <!-- 消息统计 -->
          <div class="message-stats">
            <div class="stat-item unread">
              <span class="stat-label">未读消息</span>
              <el-badge :value="statistics.unreadCount || 0" class="stat-badge" />
            </div>
            <div class="stat-item total">
              <span class="stat-label">总消息数</span>
              <span class="stat-value">{{ statistics.totalCount || 0 }}</span>
            </div>
          </div>

          <el-divider />

          <!-- 消息分类列表 -->
          <div class="category-list">
            <div
              v-for="category in messageCategories"
              :key="category.value"
              :class="['category-item', { active: activeCategory === category.value }]"
              @click="handleCategoryChange(category.value)"
            >
              <div class="category-info">
                <el-icon :class="category.icon">
                  <component :is="category.icon" />
                </el-icon>
                <span class="category-name">{{ category.label }}</span>
              </div>
              <el-badge
                v-if="category.count > 0"
                :value="category.count"
                class="category-badge"
              />
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧消息列表区域 -->
      <el-col :span="19" class="main-content">
        <el-card class="message-list-card">
          <!-- 顶部搜索和操作区域 -->
          <template #header>
            <div class="list-header">
              <div class="header-left">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索消息..."
                  prefix-icon="Search"
                  clearable
                  style="width: 300px;"
                  @input="handleSearch"
                />
                <el-select
                  v-model="messageStatus"
                  placeholder="消息状态"
                  style="width: 150px; margin-left: 10px;"
                  @change="handleStatusFilter"
                >
                  <el-option label="全部" value="" />
                  <el-option label="未读" value="unread" />
                  <el-option label="已读" value="read" />
                  <el-option label="已删除" value="deleted" />
                </el-select>
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  style="width: 240px; margin-left: 10px;"
                  @change="handleDateFilter"
                />
              </div>
              <div class="header-right">
                <el-button-group>
                  <el-button
                    icon="Refresh"
                    @click="refreshMessages"
                    :loading="loading"
                  >
                    刷新
                  </el-button>
                  <el-button
                    icon="Download"
                    @click="exportMessages"
                  >
                    导出
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </template>

          <!-- 消息列表 -->
          <div class="message-list" v-loading="loading">
            <!-- 批量操作栏 -->
            <div class="batch-actions" v-if="selectedMessages.length > 0">
              <el-checkbox
                v-model="selectAll"
                :indeterminate="isIndeterminate"
                @change="handleSelectAll"
              >
                全选
              </el-checkbox>
              <span class="selection-info">
                已选择 {{ selectedMessages.length }} 条消息
              </span>
              <div class="action-buttons">
                <el-button
                  size="small"
                  type="primary"
                  icon="Check"
                  @click="batchMarkAsRead"
                >
                  标记已读
                </el-button>
                <el-button
                  size="small"
                  type="warning"
                  icon="Close"
                  @click="batchMarkAsUnread"
                >
                  标记未读
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  icon="Delete"
                  @click="batchDelete"
                >
                  批量删除
                </el-button>
              </div>
            </div>

            <!-- 消息项列表 -->
            <div class="message-items">
              <div
                v-for="message in messageList"
                :key="message.id"
                :class="['message-item', {
                  unread: message.status === 'unread',
                  selected: selectedMessages.some(m => m.id === message.id)
                }]"
                @click="toggleMessageSelection(message)"
              >
                <div class="message-left">
                  <el-checkbox
                    :model-value="selectedMessages.some(m => m.id === message.id)"
                    @change="toggleMessageSelection(message)"
                    @click.stop
                  />
                  <div class="message-type-icon">
                    <el-icon :class="getMessageTypeIcon(message.messageType)">
                      <component :is="getMessageTypeIcon(message.messageType)" />
                    </el-icon>
                  </div>
                </div>

                <div class="message-content" @click="viewMessageDetail(message)">
                  <div class="message-header">
                    <span class="message-title">{{ message.title }}</span>
                    <div class="message-meta">
                      <el-tag
                        :type="getMessageTypeTagType(message.messageType)"
                        size="small"
                      >
                        {{ getMessageTypeLabel(message.messageType) }}
                      </el-tag>
                      <el-tag
                        :type="getPriorityTagType(message.priority)"
                        size="small"
                      >
                        {{ getPriorityLabel(message.priority) }}
                      </el-tag>
                      <span class="message-time">{{ formatTime(message.createAt) }}</span>
                    </div>
                  </div>
                  <div class="message-preview">
                    {{ message.content }}
                  </div>
                  <div class="message-footer">
                    <span class="message-sender">发送者: {{ message.senderName }}</span>
                    <div class="message-actions">
                      <el-button
                        v-if="message.status === 'unread'"
                        type="text"
                        size="small"
                        icon="Check"
                        @click.stop="markAsRead(message.id)"
                      >
                        标记已读
                      </el-button>
                      <el-button
                        type="text"
                        size="small"
                        icon="Delete"
                        @click.stop="deleteMessage(message)"
                      >
                        删除
                      </el-button>
                      <el-button
                        v-if="message.canRecall"
                        type="text"
                        size="small"
                        icon="RefreshLeft"
                        @click.stop="handleRecallMessage(message)"
                      >
                        撤回
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 空状态 -->
              <el-empty
                v-if="messageList.length === 0 && !loading"
                description="暂无消息"
                :image-size="120"
              />
            </div>

            <!-- 分页 -->
            <div class="pagination-wrapper">
              <el-pagination
                v-model:current-page="pagination.currentPage"
                v-model:page-size="pagination.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="pagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 消息详情弹窗 -->
    <el-dialog
      v-model="messageDetailVisible"
      :title="currentMessage.title"
      width="700px"
      destroy-on-close
    >
      <div class="message-detail">
        <div class="detail-header">
          <div class="detail-meta">
            <el-tag :type="getMessageTypeTagType(currentMessage.messageType)">
              {{ getMessageTypeLabel(currentMessage.messageType) }}
            </el-tag>
            <el-tag :type="getPriorityTagType(currentMessage.priority)" size="small">
              {{ getPriorityLabel(currentMessage.priority) }}
            </el-tag>
            <span class="detail-time">{{ formatTime(currentMessage.createAt) }}</span>
          </div>
          <div class="detail-sender">
            <span>发送者: {{ currentMessage.senderName }}</span>
          </div>
        </div>

        <el-divider />

        <div class="detail-content">
          <div class="content-text" v-html="currentMessage.content"></div>
        </div>

        <div v-if="currentMessage.attachments && currentMessage.attachments.length > 0" class="detail-attachments">
          <el-divider />
          <h4>附件</h4>
          <div class="attachment-list">
            <el-link
              v-for="attachment in currentMessage.attachments"
              :key="attachment.id"
              :href="attachment.url"
              target="_blank"
              type="primary"
              class="attachment-item"
            >
              <el-icon><Paperclip /></el-icon>
              {{ attachment.name }}
            </el-link>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="messageDetailVisible = false">关闭</el-button>
          <el-button
            v-if="currentMessage.status === 'unread'"
            type="primary"
            @click="markAsReadAndClose(currentMessage.id)"
          >
            标记已读并关闭
          </el-button>
          <el-button
            type="danger"
            @click="deleteCurrentMessage"
          >
            删除消息
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 消息设置弹窗 -->
    <el-dialog
      v-model="settingsVisible"
      title="消息设置"
      width="600px"
    >
      <el-form
        :model="messageSettings"
        :rules="settingsRules"
        ref="settingsFormRef"
        label-width="120px"
      >
        <el-form-item label="通知设置" prop="notifications">
          <el-checkbox-group v-model="messageSettings.notifications">
            <el-checkbox label="system">系统通知</el-checkbox>
            <el-checkbox label="sports">赛事通知</el-checkbox>
            <el-checkbox label="score">成绩通知</el-checkbox>
            <el-checkbox label="schedule">赛程提醒</el-checkbox>
            <el-checkbox label="announcement">公告通知</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="推送方式" prop="pushMethods">
          <el-checkbox-group v-model="messageSettings.pushMethods">
            <el-checkbox label="app">APP推送</el-checkbox>
            <el-checkbox label="email">邮件通知</el-checkbox>
            <el-checkbox label="sms">短信通知</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="免打扰时段">
          <el-time-picker
            v-model="messageSettings.doNotDisturb.start"
            placeholder="开始时间"
            format="HH:mm"
            value-format="HH:mm"
            style="width: 120px; margin-right: 10px;"
          />
          <span style="margin-right: 10px;">至</span>
          <el-time-picker
            v-model="messageSettings.doNotDisturb.end"
            placeholder="结束时间"
            format="HH:mm"
            value-format="HH:mm"
            style="width: 120px;"
          />
        </el-form-item>

        <el-form-item label="消息保留天数">
          <el-input-number
            v-model="messageSettings.retentionDays"
            :min="1"
            :max="365"
            controls-position="right"
          />
          <span style="margin-left: 10px;">天</span>
        </el-form-item>

        <el-form-item label="自动标记已读">
          <el-switch v-model="messageSettings.autoMarkRead" />
          <span style="margin-left: 10px; color: #909399;">查看消息后自动标记为已读</span>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="settingsVisible = false">取消</el-button>
          <el-button type="primary" @click="saveSettings" :loading="savingSettings">
            保存设置
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed, watch, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import {
  getUserMessageList,
  getUserMessageById,
  markMessageAsRead,
  markMessageAsUnread,
  batchMarkMessagesAsRead,
  deleteUserMessage,
  batchDeleteUserMessages,
  getUserMessageStatistics,
  getMessageSettings,
  updateMessageSettings,
  recallMessage
} from '@/api/message'

export default {
  name: 'MessageCenter',
  setup() {
    // 响应式数据
    const loading = ref(false)
    const savingSettings = ref(false)
    const messageList = ref([])
    const selectedMessages = ref([])
    const currentMessage = ref({})
    const searchKeyword = ref('')
    const messageStatus = ref('')
    const dateRange = ref(null)
    const activeCategory = ref('all')

    // WebSocket 实例
    const websocket = ref(null)
    const wsConnected = ref(false)
    const wsReconnectAttempts = ref(0)
    const wsMaxReconnectAttempts = ref(5)
    const wsReconnectInterval = ref(5000) // 重连间隔
    const heartbeatTimer = ref(null) // 心跳定时器

    // 消息分类
    const messageCategories = ref([
      { label: '全部消息', value: 'all', icon: 'Message', count: 0 },
      { label: '未读消息', value: 'unread', icon: 'Bell', count: 0 },
      { label: '系统通知', value: 'system', icon: 'Setting', count: 0 },
      { label: '赛事通知', value: 'sports', icon: 'Trophy', count: 0 },
      { label: '成绩通知', value: 'score', icon: 'Medal', count: 0 },
      { label: '赛程提醒', value: 'schedule', icon: 'Calendar', count: 0 },
      { label: '公告通知', value: 'announcement', icon: 'Notification', count: 0 }
    ])

    // 统计数据
    const statistics = reactive({
      unreadCount: 0,
      totalCount: 0
    })

    // 分页数据
    const pagination = reactive({
      currentPage: 1,
      pageSize: 20,
      total: 0
    })

    // 消息设置
    const messageSettings = reactive({
      notifications: ['system', 'sports', 'score'],
      pushMethods: ['app'],
      doNotDisturb: {
        start: '22:00',
        end: '08:00'
      },
      retentionDays: 30,
      autoMarkRead: true
    })

    // 对话框状态
    const messageDetailVisible = ref(false)
    const settingsVisible = ref(false)

    // 表单引用
    const settingsFormRef = ref(null)

    // 表单验证规则
    const settingsRules = {
      notifications: [
        { required: true, message: '请至少选择一种通知类型', trigger: 'change' }
      ],
      pushMethods: [
        { required: true, message: '请至少选择一种推送方式', trigger: 'change' }
      ]
    }

    // 计算属性
    const selectAll = computed({
      get: () => selectedMessages.value.length === messageList.value.length && messageList.value.length > 0,
      set: (value) => {
        if (value) {
          selectedMessages.value = [...messageList.value]
        } else {
          selectedMessages.value = []
        }
      }
    })

    const isIndeterminate = computed(() => {
      return selectedMessages.value.length > 0 && selectedMessages.value.length < messageList.value.length
    })

    // 生命周期钩子
    onMounted(() => {
      loadMessages()
      loadStatistics()
      loadMessageSettings()
      initWebSocket()
    })

    onBeforeUnmount(() => {
      closeWebSocket()
    })

    // 监听器
    watch(activeCategory, () => {
      pagination.currentPage = 1
      loadMessages()
    })

    // WebSocket 相关方法
    const initWebSocket = () => {
      // 根据当前环境获取WebSocket地址
      const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
      const wsUrl = `${protocol}//${window.location.host}/websocket/message`

      try {
        websocket.value = new WebSocket(wsUrl)
        setupWebSocketEvents()
      } catch (error) {
        console.error('WebSocket连接失败:', error)
        ElMessage.error('实时消息连接失败，将使用定时刷新')
        setupFallbackPolling()
      }
    }

    const setupWebSocketEvents = () => {
      if (!websocket.value) return

      websocket.value.onopen = () => {
        console.log('WebSocket连接成功')
        wsConnected.value = true
        wsReconnectAttempts.value = 0
        startHeartbeat()
        ElMessage.success('实时消息已连接')
      }

      websocket.value.onmessage = (event) => {
        handleWebSocketMessage(event)
      }

      websocket.value.onclose = () => {
        console.log('WebSocket连接关闭')
        wsConnected.value = false
        stopHeartbeat()
        handleWebSocketDisconnect()
      }

      websocket.value.onerror = (error) => {
        console.error('WebSocket错误:', error)
        wsConnected.value = false
        ElMessage.warning('实时消息连接异常')
      }
    }

    const handleWebSocketMessage = (event) => {
      try {
        const data = JSON.parse(event.data)

        switch (data.type) {
          case 'new_message':
            handleNewMessage(data.payload)
            break
          case 'message_read':
            handleMessageReadStatus(data.payload)
            break
          case 'message_deleted':
            handleMessageDeleted(data.payload)
            break
          case 'heartbeat':
            handleHeartbeatResponse()
            break
          default:
            console.log('未知消息类型:', data.type)
        }
      } catch (error) {
        console.error('处理WebSocket消息失败:', error)
      }
    }

    const handleNewMessage = (messageData) => {
      // 显示桌面通知
      if (Notification.permission === 'granted') {
        showDesktopNotification(messageData)
      }

      // 显示浏览器内通知
      ElNotification({
        title: messageData.title,
        message: messageData.content,
        type: getNotificationType(messageData.messageType),
        duration: 5000,
        onClick: () => {
          viewMessageDetail(messageData)
        }
      })

      // 播放提示音
      playNotificationSound()

      // 刷新消息列表和统计
      loadMessages()
      loadStatistics()
    }

    const handleMessageReadStatus = (data) => {
      // 更新消息状态
      const message = messageList.value.find(m => m.id === data.messageId)
      if (message) {
        message.status = 'read'
      }

      // 更新统计数据
      if (data.statistics) {
        Object.assign(statistics, data.statistics)
      }
    }

    const handleMessageDeleted = (data) => {
      // 从列表中移除消息
      const index = messageList.value.findIndex(m => m.id === data.messageId)
      if (index > -1) {
        messageList.value.splice(index, 1)
      }

      // 更新统计数据
      if (data.statistics) {
        Object.assign(statistics, data.statistics)
      }
    }

    const showDesktopNotification = (messageData) => {
      const notification = new Notification(messageData.title, {
        body: messageData.content,
        icon: '/favicon.ico',
        tag: `message_${messageData.id}`,
        requireInteraction: false
      })

      notification.onclick = () => {
        window.focus()
        viewMessageDetail(messageData)
        notification.close()
      }

      // 5秒后自动关闭
      setTimeout(() => {
        notification.close()
      }, 5000)
    }

    const getNotificationType = (messageType) => {
      const typeMap = {
        system: 'info',
        sports: 'success',
        score: 'warning',
        schedule: 'info',
        announcement: 'primary',
        urgent: 'error'
      }
      return typeMap[messageType] || 'info'
    }

    const playNotificationSound = () => {
      try {
        const audio = new Audio('/notification.mp3')
        audio.volume = 0.5
        audio.play().catch(() => {
          // 忽略自动播放被阻止的错误
        })
      } catch (error) {
        // 忽略音频播放错误
      }
    }

    const startHeartbeat = () => {
      stopHeartbeat() // 先停止之前的心跳
      heartbeatTimer.value = setInterval(() => {
        if (websocket.value && wsConnected.value) {
          websocket.value.send(JSON.stringify({ type: 'heartbeat' }))
        }
      }, 30000) // 每30秒发送一次心跳
    }

    const stopHeartbeat = () => {
      if (heartbeatTimer.value) {
        clearInterval(heartbeatTimer.value)
        heartbeatTimer.value = null
      }
    }

    const handleHeartbeatResponse = () => {
      // 收到心跳响应，说明连接正常
      console.log('WebSocket心跳正常')
    }

    const handleWebSocketDisconnect = () => {
      // 尝试重连
      if (wsReconnectAttempts.value < wsMaxReconnectAttempts.value) {
        wsReconnectAttempts.value++
        console.log(`WebSocket重连尝试 ${wsReconnectAttempts.value}/${wsMaxReconnectAttempts.value}`)

        setTimeout(() => {
          ElMessage.info(`正在尝试重连(${wsReconnectAttempts.value}/${wsMaxReconnectAttempts.value})...`)
          initWebSocket()
        }, wsReconnectInterval.value)
      } else {
        ElMessage.error('实时消息连接失败，已达到最大重连次数，将使用定时刷新')
        setupFallbackPolling()
      }
    }

    const setupFallbackPolling = () => {
      // 如果WebSocket连接失败，使用定时轮询作为后备方案
      setInterval(() => {
        if (!wsConnected.value) {
          loadMessages()
          loadStatistics()
        }
      }, 30000) // 每30秒刷新一次
    }

    const closeWebSocket = () => {
      stopHeartbeat()

      if (websocket.value) {
        websocket.value.close()
        websocket.value = null
      }
      wsConnected.value = false
    }

    const requestNotificationPermission = async () => {
      if ('Notification' in window && Notification.permission === 'default') {
        try {
          const permission = await Notification.requestPermission()
          if (permission === 'granted') {
            ElMessage.success('桌面通知权限已开启')
          }
        } catch (error) {
          console.error('请求通知权限失败:', error)
        }
      }
    }

    // 初始化时请求通知权限
    requestNotificationPermission()

    // 方法
    const loadMessages = async () => {
      loading.value = true
      try {
        const params = {
          keyword: searchKeyword.value,
          messageType: activeCategory.value === 'all' || activeCategory.value === 'unread' ? '' : activeCategory.value,
          status: activeCategory.value === 'unread' ? 'unread' : messageStatus.value,
          startDate: dateRange.value?.[0],
          endDate: dateRange.value?.[1]
        }

        const response = await getUserMessageList(pagination.currentPage, pagination.pageSize, params)
        if (response.code === 200) {
          messageList.value = response.data.records || []
          pagination.total = response.data.total || 0

          // 更新分类计数
          updateCategoryCounts()
        }
      } catch (error) {
        console.error('加载消息列表失败:', error)
        ElMessage.error('加载消息列表失败')
      } finally {
        loading.value = false
      }
    }

    const loadStatistics = async () => {
      try {
        const response = await getUserMessageStatistics()
        if (response.code === 200) {
          Object.assign(statistics, response.data)

          // 更新未读消息计数
          const unreadCategory = messageCategories.value.find(c => c.value === 'unread')
          if (unreadCategory) {
            unreadCategory.count = statistics.unreadCount
          }
        }
      } catch (error) {
        console.error('加载统计数据失败:', error)
      }
    }

    const loadMessageSettings = async () => {
      try {
        const response = await getMessageSettings()
        if (response.code === 200) {
          Object.assign(messageSettings, response.data)
        }
      } catch (error) {
        console.error('加载消息设置失败:', error)
      }
    }

    const updateCategoryCounts = () => {
      // 根据消息列表更新各分类的计数
      const counts = {
        all: messageList.value.length,
        unread: messageList.value.filter(m => m.status === 'unread').length,
        system: messageList.value.filter(m => m.messageType === 'system').length,
        sports: messageList.value.filter(m => m.messageType === 'sports').length,
        score: messageList.value.filter(m => m.messageType === 'score').length,
        schedule: messageList.value.filter(m => m.messageType === 'schedule').length,
        announcement: messageList.value.filter(m => m.messageType === 'announcement').length
      }

      messageCategories.value.forEach(category => {
        if (category.value !== 'unread') {
          category.count = counts[category.value] || 0
        }
      })
    }

    const handleCategoryChange = (category) => {
      activeCategory.value = category
    }

    const handleSearch = () => {
      pagination.currentPage = 1
      loadMessages()
    }

    const handleStatusFilter = () => {
      pagination.currentPage = 1
      loadMessages()
    }

    const handleDateFilter = () => {
      pagination.currentPage = 1
      loadMessages()
    }

    const refreshMessages = () => {
      loadMessages()
      loadStatistics()
    }

    const handleSizeChange = (size) => {
      pagination.pageSize = size
      loadMessages()
    }

    const handleCurrentChange = (page) => {
      pagination.currentPage = page
      loadMessages()
    }

    const toggleMessageSelection = (message) => {
      const index = selectedMessages.value.findIndex(m => m.id === message.id)
      if (index > -1) {
        selectedMessages.value.splice(index, 1)
      } else {
        selectedMessages.value.push(message)
      }
    }

    const handleSelectAll = () => {
      // 计算属性会处理
    }

    const viewMessageDetail = async (message) => {
      try {
        const response = await getUserMessageById(message.id)
        if (response.code === 200) {
          currentMessage.value = response.data
          messageDetailVisible.value = true

          // 如果是未读消息，自动标记为已读
          if (message.status === 'unread' && messageSettings.autoMarkRead) {
            await markAsRead(message.id)
          }
        }
      } catch (error) {
        console.error('获取消息详情失败:', error)
        ElMessage.error('获取消息详情失败')
      }
    }

    const markAsRead = async (messageId) => {
      try {
        const response = await markMessageAsRead(messageId)
        if (response.code === 200) {
          ElMessage.success('已标记为已读')
          loadMessages()
          loadStatistics()
        }
      } catch (error) {
        console.error('标记已读失败:', error)
        ElMessage.error('标记已读失败')
      }
    }

    const markAsUnread = async (messageId) => {
      try {
        const response = await markMessageAsUnread(messageId)
        if (response.code === 200) {
          ElMessage.success('已标记为未读')
          loadMessages()
          loadStatistics()
        }
      } catch (error) {
        console.error('标记未读失败:', error)
        ElMessage.error('标记未读失败')
      }
    }

    const batchMarkAsRead = async () => {
      if (selectedMessages.value.length === 0) {
        ElMessage.warning('请选择要标记的消息')
        return
      }

      try {
        const messageIds = selectedMessages.value.map(m => m.id)
        const response = await batchMarkMessagesAsRead(messageIds)
        if (response.code === 200) {
          ElMessage.success('批量标记已读成功')
          selectedMessages.value = []
          loadMessages()
          loadStatistics()
        }
      } catch (error) {
        console.error('批量标记已读失败:', error)
        ElMessage.error('批量标记已读失败')
      }
    }

    const batchMarkAsUnread = async () => {
      if (selectedMessages.value.length === 0) {
        ElMessage.warning('请选择要标记的消息')
        return
      }

      try {
        // 批量标记未读的API
        ElMessage.success('批量标记未读成功')
        selectedMessages.value = []
        loadMessages()
        loadStatistics()
      } catch (error) {
        console.error('批量标记未读失败:', error)
        ElMessage.error('批量标记未读失败')
      }
    }

    const deleteMessage = (message) => {
      ElMessageBox.confirm(
        `确定要删除消息"${message.title}"吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const response = await deleteUserMessage(message.id)
          if (response.code === 200) {
            ElMessage.success('删除成功')
            loadMessages()
            loadStatistics()
          }
        } catch (error) {
          console.error('删除消息失败:', error)
          ElMessage.error('删除消息失败')
        }
      })
    }

    const batchDelete = () => {
      if (selectedMessages.value.length === 0) {
        ElMessage.warning('请选择要删除的消息')
        return
      }

      ElMessageBox.confirm(
        `确定要删除选中的 ${selectedMessages.value.length} 条消息吗？`,
        '确认批量删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const messageIds = selectedMessages.value.map(m => m.id)
          const response = await batchDeleteUserMessages(messageIds)
          if (response.code === 200) {
            ElMessage.success('批量删除成功')
            selectedMessages.value = []
            loadMessages()
            loadStatistics()
          }
        } catch (error) {
          console.error('批量删除失败:', error)
          ElMessage.error('批量删除失败')
        }
      })
    }

    const handleRecallMessage = (message) => {
      ElMessageBox.confirm(
        `确定要撤回消息"${message.title}"吗？撤回后消息将无法恢复。`,
        '确认撤回',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          const response = await recallMessage(message.id)
          if (response.code === 200) {
            ElMessage.success('撤回成功')
            loadMessages()
            loadStatistics()
          }
        } catch (error) {
          console.error('撤回消息失败:', error)
          ElMessage.error('撤回消息失败')
        }
      })
    }

    const markAsReadAndClose = async (messageId) => {
      try {
        await markAsRead(messageId)
        messageDetailVisible.value = false
      } catch (error) {
        console.error('标记已读失败:', error)
      }
    }

    const deleteCurrentMessage = () => {
      if (currentMessage.value) {
        deleteMessage(currentMessage.value)
        messageDetailVisible.value = false
      }
    }

    const exportMessages = () => {
      // 导出功能
      ElMessage.info('导出功能开发中...')
    }

    const showSettingsDialog = () => {
      settingsVisible.value = true
    }

    const saveSettings = async () => {
      try {
        await settingsFormRef.value.validate()
        savingSettings.value = true

        const response = await updateMessageSettings(messageSettings)
        if (response.code === 200) {
          ElMessage.success('设置保存成功')
          settingsVisible.value = false
        }
      } catch (error) {
        console.error('保存设置失败:', error)
        ElMessage.error('保存设置失败')
      } finally {
        savingSettings.value = false
      }
    }

    const formatTime = (time) => {
      if (!time) return ''
      const date = new Date(time)
      const now = new Date()
      const diff = now - date

      if (diff < 60000) { // 1分钟内
        return '刚刚'
      } else if (diff < 3600000) { // 1小时内
        return `${Math.floor(diff / 60000)}分钟前`
      } else if (diff < 86400000) { // 1天内
        return `${Math.floor(diff / 3600000)}小时前`
      } else if (diff < 604800000) { // 7天内
        return `${Math.floor(diff / 86400000)}天前`
      } else {
        return date.toLocaleDateString('zh-CN')
      }
    }

    // 辅助方法
    const getMessageTypeLabel = (type) => {
      const typeMap = {
        system: '系统通知',
        sports: '赛事通知',
        score: '成绩通知',
        schedule: '赛程提醒',
        announcement: '公告通知',
        urgent: '紧急通知'
      }
      return typeMap[type] || type
    }

    const getMessageTypeTagType = (type) => {
      const typeMap = {
        system: '',
        sports: 'success',
        score: 'warning',
        schedule: 'info',
        announcement: 'primary',
        urgent: 'danger'
      }
      return typeMap[type] || ''
    }

    const getMessageTypeIcon = (type) => {
      const iconMap = {
        system: 'Setting',
        sports: 'Trophy',
        score: 'Medal',
        schedule: 'Calendar',
        announcement: 'Notification',
        urgent: 'WarningFilled'
      }
      return iconMap[type] || 'Message'
    }

    const getPriorityLabel = (priority) => {
      const priorityMap = {
        low: '低',
        medium: '中',
        high: '高',
        urgent: '紧急'
      }
      return priorityMap[priority] || priority
    }

    const getPriorityTagType = (priority) => {
      const priorityMap = {
        low: 'info',
        medium: '',
        high: 'warning',
        urgent: 'danger'
      }
      return priorityMap[priority] || ''
    }

    return {
      // 响应式数据
      loading,
      savingSettings,
      messageList,
      selectedMessages,
      currentMessage,
      searchKeyword,
      messageStatus,
      dateRange,
      activeCategory,
      messageCategories,
      statistics,
      pagination,
      messageSettings,
      messageDetailVisible,
      settingsVisible,

      // WebSocket 相关数据
      wsConnected,

      // 表单引用
      settingsFormRef,

      // 表单验证规则
      settingsRules,

      // 计算属性
      selectAll,
      isIndeterminate,

      // 方法
      loadMessages,
      handleCategoryChange,
      handleSearch,
      handleStatusFilter,
      handleDateFilter,
      refreshMessages,
      handleSizeChange,
      handleCurrentChange,
      toggleMessageSelection,
      handleSelectAll,
      viewMessageDetail,
      markAsRead,
      markAsUnread,
      batchMarkAsRead,
      batchMarkAsUnread,
      deleteMessage,
      batchDelete,
      handleRecallMessage,
      markAsReadAndClose,
      deleteCurrentMessage,
      exportMessages,
      showSettingsDialog,
      saveSettings,
      formatTime,

      // 辅助方法
      getMessageTypeLabel,
      getMessageTypeTagType,
      getMessageTypeIcon,
      getPriorityLabel,
      getPriorityTagType
    }
  }
}
</script>

<style lang="scss" scoped>
.message-center {
  padding: 20px;
  height: 100%;

  .breadcrumb {
    margin-bottom: 20px;
  }

  .ws-status-indicator {
    position: fixed;
    top: 80px;
    right: 30px;
    z-index: 1000;

    .status-dot {
      display: flex;
      align-items: center;
      padding: 8px 16px;
      border-radius: 20px;
      font-size: 12px;
      font-weight: 500;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;
      cursor: pointer;

      &.connected {
        background-color: #f0f9ff;
        color: #1890ff;
        border: 1px solid #91d5ff;

        &::before {
          content: '';
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: #52c41a;
          margin-right: 8px;
          animation: pulse 2s infinite;
        }
      }

      &.disconnected {
        background-color: #fff2f0;
        color: #ff4d4f;
        border: 1px solid #ffccc7;

        &::before {
          content: '';
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: #ff4d4f;
          margin-right: 8px;
        }
      }

      .status-text {
        white-space: nowrap;
      }

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }
    }
  }

  @keyframes pulse {
    0% {
      box-shadow: 0 0 0 0 rgba(82, 196, 26, 0.7);
    }
    70% {
      box-shadow: 0 0 0 10px rgba(82, 196, 26, 0);
    }
    100% {
      box-shadow: 0 0 0 0 rgba(82, 196, 26, 0);
    }
  }

  .main-container {
    height: calc(100vh - 120px);

    .sidebar {
      height: 100%;

      .category-card {
        height: 100%;

        .card-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .message-stats {
          .stat-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;

            &.unread {
              .stat-label {
                color: #f56c6c;
                font-weight: 500;
              }
            }

            &.total {
              .stat-value {
                color: #909399;
              }
            }

            .stat-badge {
              :deep(.el-badge__content) {
                background-color: #f56c6c;
              }
            }
          }
        }

        .category-list {
          .category-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px;
            margin-bottom: 8px;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s;

            &:hover {
              background-color: #f5f7fa;
            }

            &.active {
              background-color: #ecf5ff;
              color: #409eff;

              .category-name {
                font-weight: 500;
              }
            }

            .category-info {
              display: flex;
              align-items: center;

              .el-icon {
                margin-right: 8px;
                font-size: 16px;
              }

              .category-name {
                font-size: 14px;
              }
            }

            .category-badge {
              :deep(.el-badge__content) {
                background-color: #f56c6c;
              }
            }
          }
        }
      }
    }

    .main-content {
      height: 100%;

      .message-list-card {
        height: 100%;
        display: flex;
        flex-direction: column;

        :deep(.el-card__body) {
          flex: 1;
          display: flex;
          flex-direction: column;
          overflow: hidden;
        }

        .list-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 0;
        }

        .message-list {
          flex: 1;
          display: flex;
          flex-direction: column;
          overflow: hidden;

          .batch-actions {
            display: flex;
            align-items: center;
            padding: 15px;
            background-color: #f8f9fa;
            border-bottom: 1px solid #ebeef5;
            margin-bottom: 15px;

            .selection-info {
              margin-left: 15px;
              color: #606266;
              font-size: 14px;
            }

            .action-buttons {
              margin-left: auto;
              display: flex;
              gap: 10px;
            }
          }

          .message-items {
            flex: 1;
            overflow-y: auto;
            padding: 0 15px;

            .message-item {
              display: flex;
              padding: 15px;
              border-bottom: 1px solid #f0f0f0;
              cursor: pointer;
              transition: all 0.3s;

              &:hover {
                background-color: #fafafa;
              }

              &.unread {
                background-color: #fef7f7;
                border-left: 3px solid #f56c6c;

                .message-title {
                  font-weight: 600;
                }
              }

              &.selected {
                background-color: #ecf5ff;
                border-left: 3px solid #409eff;
              }

              .message-left {
                display: flex;
                align-items: center;
                margin-right: 15px;

                .message-type-icon {
                  margin-left: 10px;

                  .el-icon {
                    font-size: 18px;
                    color: #909399;
                  }
                }
              }

              .message-content {
                flex: 1;

                .message-header {
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                  margin-bottom: 8px;

                  .message-title {
                    font-size: 15px;
                    color: #303133;
                    flex: 1;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                  }

                  .message-meta {
                    display: flex;
                    align-items: center;
                    gap: 8px;

                    .message-time {
                      color: #909399;
                      font-size: 12px;
                    }
                  }
                }

                .message-preview {
                  color: #606266;
                  font-size: 13px;
                  line-height: 1.5;
                  margin-bottom: 10px;
                  display: -webkit-box;
                  -webkit-line-clamp: 2;
                  -webkit-box-orient: vertical;
                  overflow: hidden;
                }

                .message-footer {
                  display: flex;
                  justify-content: space-between;
                  align-items: center;

                  .message-sender {
                    color: #909399;
                    font-size: 12px;
                  }

                  .message-actions {
                    display: flex;
                    gap: 5px;
                    opacity: 0;
                    transition: opacity 0.3s;
                  }
                }
              }

              &:hover .message-actions {
                opacity: 1;
              }
            }
          }

          .pagination-wrapper {
            padding: 20px 0;
            display: flex;
            justify-content: center;
          }
        }
      }
    }
  }

  .message-detail {
    .detail-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;

      .detail-meta {
        display: flex;
        align-items: center;
        gap: 10px;

        .detail-time {
          color: #909399;
          font-size: 14px;
        }
      }

      .detail-sender {
        color: #606266;
        font-size: 14px;
      }
    }

    .detail-content {
      margin-bottom: 20px;

      .content-text {
        line-height: 1.6;
        color: #303133;
        white-space: pre-wrap;
      }
    }

    .detail-attachments {
      h4 {
        margin-bottom: 10px;
        color: #303133;
      }

      .attachment-list {
        display: flex;
        flex-direction: column;
        gap: 8px;

        .attachment-item {
          display: flex;
          align-items: center;
          gap: 5px;
        }
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .message-center {
    .main-container {
      .sidebar {
        margin-bottom: 20px;
      }

      .main-content {
        height: auto;
      }
    }
  }
}

@media (max-width: 768px) {
  .message-center {
    padding: 10px;

    .ws-status-indicator {
      top: 70px;
      right: 15px;

      .status-dot {
        padding: 6px 12px;
        font-size: 11px;
      }
    }

    .list-header {
      flex-direction: column;
      gap: 15px;
      align-items: stretch !important;

      .header-left {
        flex-direction: column;
        gap: 10px;

        .el-input,
        .el-select,
        .el-date-picker {
          width: 100% !important;
          margin-left: 0 !important;
        }
      }

      .header-right {
        justify-content: center;
      }
    }

    .message-item {
      .message-header {
        flex-direction: column;
        align-items: flex-start !important;
        gap: 8px;
      }

      .message-footer {
        flex-direction: column;
        align-items: flex-start !important;
        gap: 10px;

        .message-actions {
          opacity: 1 !important;
        }
      }
    }
  }
}
</style>